package com.wxb.pm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxb.pm.Exception.BusinessException;
import com.wxb.pm.Model.domain.User;
import com.wxb.pm.Model.requset.UserLoginRequest;
import com.wxb.pm.Model.requset.UserRegisterRequest;
import com.wxb.pm.common.BaseResponse;
import com.wxb.pm.common.ErrorCode;
import com.wxb.pm.common.ResponseUtils;
import com.wxb.pm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.wxb.pm.constant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if(userRegisterRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword =userRegisterRequest.getUserPassword();
        String checkPassword =userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResponseUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        if(userLoginRequest == null){
            return null;
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword =userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            return null;
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResponseUtils.success(user);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> userSearch(String username,HttpServletRequest request){
        if (!userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(username)){
            //模糊查询
            queryWrapper.like("username",username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResponseUtils.success(list);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null){
            return null;
        }
        long userId = currentUser.getId();
        User user = userService.getById(userId);
        User sfetyUser = userService.getSafetyUser(user);
        return ResponseUtils.success(sfetyUser);
    }

    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id,HttpServletRequest request){
        if (!userService.isAdmin(request)){
            return null;
        }
        if (id <= 0){
            return null;
        }
        boolean b = userService.removeById(id);
        return ResponseUtils.success(b);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout( HttpServletRequest request){
        if(request == null){
            return null;
        }
        int i = userService.userLogout(request);
        return ResponseUtils.success(i);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList){
        if (tagNameList == null)
        {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUsersByTags(tagNameList);
        return ResponseUtils.success(userList);
    }

    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest request){
        if(user ==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        int result = userService.updateUser(user, loginUser);
        return ResponseUtils.success(result);
    }

    @GetMapping("/index")
    public BaseResponse<Page<User>> userSearch(long pageSize,long pageNum,HttpServletRequest request){
        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        //key拼接当前用户的id
        String key = String.format("pm:user:index:%s",loginUser.getId());
        //有缓存，读缓存
        Page<User> userPage = (Page<User>)operations.get(key);
        if (userPage!=null){
            return ResponseUtils.success(userPage);
        }
        //无缓存，读数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum,pageSize),queryWrapper);
        //写缓存
        try {
            operations.set(key,userPage,1, TimeUnit.HOURS);
        } catch (Exception e) {
            log.error("redis set key error",e);
        }
        return ResponseUtils.success(userPage);
    }

    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num,HttpServletRequest request){
        if (num <= 0 || num >20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        return ResponseUtils.success(userService.matchUsers(num,loginUser));
    }
}
